<?php

App::uses('AdminController', 'Controller');

class AdminUkusiController extends AdminController {
    
    public $uses = array( 'Taste', 'TasteGroup' );
    
    public function index() {
        $tastes = $this->Taste->getAll();
        $groups = $this->TasteGroup->find('list');
        
        $this->set(compact('tastes', 'groups'));
    }
    
    public function create($groupId) {
        $this->layout = 'ajax';
        $this->set('data', $this->Taste->create(array(
            'Taste' => array('taste_group_id' => $groupId)
        )));
        $this->render('form');
    }
    
    public function edit($id) {
        $this->layout = 'ajax';
        $this->set('data', $this->Taste->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $this->autoRender = false;
        $response = array('status'=>200, 'message' => 'Sačuvano');
        
        if (! $this->request->is('post')) {
            $response = array('status'=>500, 'message' => 'Nepravilan zahtev');
        } else {
            $data = $this->data;
            $this->Taste->create($data);
            
            if (! $this->Taste->validates()) {
                $response = array('status'=>500, 'message' => 'Uneti podaci nisu validni.');
            }
            
            if (! $this->Taste->save($data)) {
                $response = array('status'=>500, 'message' => 'Greška pri čuvanju podataka.');
            }
        }
        
        $this->set('response', $response);
        $this->render('/Elements/iframe_post_back');
    }
    
    public function delete($id) {
        $this->autoRender = false;
        if ($this->Taste->delete($id)) {
            echo 'Ukus je obrisan.';
        } else {
            $this->errorHeader('Brisanje nije uspelo');
        }
    }
    
    public function save_group() {
        $this->autoRender = false;
        
        if ($this->request->is('post')) {
            $data = $this->data;
            if (! empty($data)) {
                $this->TasteGroup->create($data);
                if ($this->TasteGroup->validates()) {
                    if ($this->TasteGroup->save($data)) {
                        die("Grupa je uspešno sačuvana.");
                    }
                }
            }
        }
            
        $this->errorHeader('Neispravan zahtev.');
    }
    
    public function delete_group($id) {
        $this->autoRender = false;
        if ($this->TasteGroup->delete($id)) {
            echo 'Grupa je obrisana.';
        } else {
            $this->errorHeader('Brisanje nije uspelo');
        }
    }
    
}